// 主应用文件
const express = require('express');
const path = require('path');
const session = require('express-session');
const flash = require('connect-flash');
const { Op } = require('sequelize');

// 导入路由
const authRoutes = require('./routes/authRoutes');
const adminRoutes = require('./routes/adminRoutes');

// 初始化数据库连接
const db = require('./config/sequelize');

const app = express();
const PORT = process.env.PORT || 3000;

// 设置模板引擎
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'public/views'));

// 中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));

// 会话管理
app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false }
}));

// 消息闪现
app.use(flash());

// 全局变量
app.use((req, res, next) => {
  res.locals.success_msg = req.flash('success');
  res.locals.error_msg = req.flash('error');
  res.locals.user = req.session.user || null;
  next();
});

// 路由
app.use('/auth', authRoutes);
app.use('/admin', adminRoutes);

// 根路径重定向到登录页
app.get('/', (req, res) => {
  res.redirect('/auth/login');
});

// 404 处理
app.use((req, res) => {
  res.status(404).render('404', { title: '页面不存在' });
});

// 启动服务器
app.listen(PORT, () => {
  // 数据库连接测试移到后台，不阻塞服务器启动
  db.authenticate()
    .then(() => {
      console.log('数据库连接成功');
    })
    .catch(error => {
      console.error('数据库连接失败:', error.message);
      console.log('注意：服务器已启动但数据库连接失败，部分功能可能不可用');
    });
  
  console.log(`服务器运行在 http://localhost:${PORT}`);
});

module.exports = app;